const _excluded = ["moduleType", "name", "x", "y", "systemType", "preId", "id", "image", "bgImage"];

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import defaultData from './defaultData';
import IndexdbHelper from './components/IndexdbHelper';
export const dbHelper = new IndexdbHelper('arch_desgin', [{
  name: 'graphDatas',
  keyPath: 'id'
}]); // // 自动保存数据

let autoSaveTimer;
export function autoSaveJson(_x, _x2) {
  return _autoSaveJson.apply(this, arguments);
}

function _autoSaveJson() {
  _autoSaveJson = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(graphData, graph) {
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (autoSaveTimer) clearTimeout(autoSaveTimer);
          return _context2.abrupt("return", new Promise(resolve => {
            autoSaveTimer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
              var isExist, data;
              return regeneratorRuntime.wrap(function _callee$(_context) {
                while (1) switch (_context.prev = _context.next) {
                  case 0:
                    _context.next = 2;
                    return dbHelper.ready();

                  case 2:
                    _context.next = 4;
                    return new Promise(resolve => setTimeout(resolve, 100));

                  case 4:
                    _context.next = 6;
                    return dbHelper.findByPk('graphDatas', '1');

                  case 6:
                    isExist = !!_context.sent;
                    data = {
                      id: '1',
                      updateTime: Date.now(),
                      data: undefined,
                      expired: window._saveInterval + 10000
                    }; // 如果有 graphData 就强制保存 graphData

                    // 如果有 graphData 就强制保存 graphData
                    if (graphData) {
                      data.data = graphData;
                    } else if (graph) {
                      // 如果没有 graphData 有graph 就保存 graph 中的数据
                      data.data = getGraphJSONData(graph);
                    } // 如果都没有 data 为 undefined 将在下次恢复时直接使用 传入的数据


                    if (!isExist) {
                      _context.next = 14;
                      break;
                    }

                    _context.next = 12;
                    return dbHelper.update('graphDatas', data);

                  case 12:
                    _context.next = 16;
                    break;

                  case 14:
                    _context.next = 16;
                    return dbHelper.create('graphDatas', data);

                  case 16:
                    resolve(1);

                  case 17:
                  case "end":
                    return _context.stop();
                }
              }, _callee);
            })), 100);
          }));

        case 2:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return _autoSaveJson.apply(this, arguments);
}

export function getLaneStyle(index) {
  const nameRectFill = ['#EAFEEC', '#F9F7E6', '#E0EEFA', '#DFE5E6'];
  const nameTextFill = ['#6A8E67', '#978A64', '#495A7F', '#859092'];
  const bottomBorderStroke = ['#9BD787', '#E1BD81', '#7BA3FC', '#859092'];
  return {
    nameRect: {
      fill: nameRectFill[index]
    },
    nameText: {
      fill: nameTextFill[index]
    },
    bottomBorder: {
      stroke: bottomBorderStroke[index]
    }
  };
}
export function getGraphData(dataSource) {
  if (!dataSource) return defaultData;
  const _dataSource$lanes = dataSource.lanes,
        lanes = _dataSource$lanes === void 0 ? [] : _dataSource$lanes,
        _dataSource$nodes = dataSource.nodes,
        nodes = _dataSource$nodes === void 0 ? [] : _dataSource$nodes,
        _dataSource$links = dataSource.links,
        links = _dataSource$links === void 0 ? [] : _dataSource$links;
  let lh = 25;
  let maxWidth = 0;
  const laneList = lanes.map((data, i) => {
    const id = data.id,
          height = data.height,
          x = data.x,
          y = data.y,
          name = data.name,
          width = data.width;
    lh += height;
    data.type = 'lane';
    data.sort = i;
    maxWidth = Math.max(maxWidth, width || 0);
    const laneData = {
      id,
      shape: 'lane',
      data,
      height,
      label: (name || '').split('').join('\n'),
      position: {
        x: x || 0,
        y: y || lh - height
      },
      attrs: getLaneStyle(i % 4)
    };
    return laneData;
  });
  const nodeList = nodes.map(createGraphNodeData);
  maxWidth = Math.max(maxWidth, ...nodeList.map(node => (node.position.x || 0) + 200));
  const linkList = links.map(link => {
    const id = link.id,
          source = link.source,
          target = link.target;
    link.type = 'link';
    return {
      id: id || `${source}_${target}`,
      shape: 'lane-edge',
      source,
      target,
      data: link
    };
  });
  return {
    width: maxWidth,
    height: lh + 25,
    laneList,
    nodeList,
    linkList
  };
} // 两行显示名称

/**
 * 用于实例详情图中任务名称显示
 * @param {string} label 需要处理的字符
 * @param {number} maxTextLen 最大长度 默认20
 * @param {number} maxLine  最大行数 默认1
 * @param {string} placehoder 中间占位字符 默认...
 */

export function getLabelText({
  label = '',
  placehoder = '...',
  maxTextLen = 20,
  maxLine = 2
}) {
  const textList = [];
  let len = 0;
  let lineCount = 0;
  (label || '').split('').every(char => {
    let crrLen;
    if (len === 0) textList[textList.length] = [];
    if (/[ilI]/.test(char)) crrLen = 0.5;else if (/[A-Z]/.test(char)) crrLen = 1.5;else if (/[^\u0000-\u00FF]/.test(char)) crrLen = 2;else crrLen = 1;

    if (lineCount === maxLine - 1 && crrLen + len >= maxTextLen - placehoder.length) {
      textList[textList.length - 1].push(placehoder);
      return false;
    }

    if (crrLen + len < maxTextLen + 1) {
      textList[textList.length - 1].push(char);
      len += crrLen;
    } else if (lineCount < maxLine) {
      textList[textList.length] = [char];
      len = crrLen;
      lineCount += 1;
    }

    return true;
  });
  return textList.map(list => list.join('')).join('\n');
}
export function nextTick(callback) {
  return Promise.resolve().then(callback);
}
export function getDndConfig(target) {
  return {
    target,
    // delegateGraphOptions
    validateNode: () => false,
    animation: true,
    getDragNode: () => {},
    getDropNode: () => {}
  };
} // 将配置数据转换成节点所需数据

export function createGraphNodeData(nodeData, config) {
  const _ref = config || {},
        graph = _ref.graph,
        assets = _ref.assets;

  const moduleType = nodeData.moduleType,
        name = nodeData.name,
        x = nodeData.x,
        y = nodeData.y,
        systemType = nodeData.systemType,
        preId = nodeData.preId,
        nodeId = nodeData.id,
        image = nodeData.image,
        bgImage = nodeData.bgImage,
        rest = _objectWithoutProperties(nodeData, _excluded);

  let id = nodeId;

  if (!id) {
    id = `${Date.now().toString(32)}_${Math.floor(Math.random() * 100000).toString(32)}`;
  }

  const data = {
    type: 'node',
    image: image || `${(moduleType || '').toLowerCase()}Module`,
    bgImage: bgImage || `${(systemType || '').toLowerCase()}System`
  };
  let position = {
    x: 0,
    y: 0
  };
  let attrs = {};

  if (x !== undefined && y !== undefined) {
    position = {
      x,
      y
    };
  } else if (graph && preId) {
    const lane = graph.getCellById(preId);

    const _lane$position = lane.position(),
          x = _lane$position.x,
          y = _lane$position.y;

    position = {
      x: x + 60,
      y: y + 10
    };
  }

  if (assets) {
    attrs = {
      itemTag: {
        xlinkHref: assets[data.image]
      },
      backgorund: {
        xlinkHref: assets[data.bgImage]
      }
    };
  }

  return {
    id,
    shape: 'lane-node',
    position,
    parent: preId,
    data: _objectSpread(_objectSpread({
      moduleType,
      name,
      systemType,
      preId,
      id
    }, rest), data),
    attrs,
    label: getLabelText({
      label: name,
      maxTextLen: 20,
      maxLine: 2,
      placehoder: '...'
    })
  };
} // 将画布中的所有元素转换成 后端保存数据

export function getGraphJSONData(graph) {
  const _graph$toJSON = graph.toJSON(),
        cells = _graph$toJSON.cells;

  const _graph$container = graph.container,
        clientWidth = _graph$container.clientWidth,
        clientHeight = _graph$container.clientHeight;
  const lanes = [];
  const nodes = [];
  const links = [];
  cells.forEach(cell => {
    const shape = cell.shape,
          position = cell.position,
          size = cell.size,
          data = cell.data,
          parent = cell.parent,
          zIndex = cell.zIndex,
          source = cell.source,
          target = cell.target;

    if (shape === 'lane-edge') {
      links.push({
        source: source.cell,
        target: target.cell,
        zIndex: zIndex || 2
      });
    } else {
      const node = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, data), size), position), {}, {
        preId: parent
      });

      if (shape === 'lane') {
        node.zIndex = zIndex || 1;
        lanes.push(node);
      } else {
        node.zIndex = zIndex || 2;
        nodes.push(node);
      }
    }
  }); // console.log(266, lanes, nodes);

  return {
    width: clientWidth,
    height: clientHeight,
    lanes,
    nodes,
    links
  };
}
export function launchFullScreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}
export function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}